home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11324 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: nuscc.nus.sg!eng30403
  2. From: eng30403@leonis.nus.sg (Tey Chee Meng)
  3. Newsgroups: comp.lang.c
  4. Subject: char/int conversion and comparison
  5. Date: 23 Mar 1996 05:27:00 GMT
  6. Organization: NUS
  7. Message-ID: <4j0234$7hi@nuscc.nus.sg>
  8. NNTP-Posting-Host: @leonis.nus.sg
  9. X-Newsreader: TIN [version 1.2 PL2]
  10.  
  11.     I got confused by the conversion and comparison between int and 
  12. char. Consider the following fragment of code :
  13.  
  14.     char foo1='a';    /* 1st line */
  15.     int foo2='a';     /* 2nd line */
  16.  
  17.     if (foo2==foo1);  /* 3rd line */
  18.  
  19.     Is this comparison guaranteed to evaluate to TRUE on all machines ?
  20.  
  21.     I have read that on different machines, char may be implemented 
  22. as signed or unsigned. Hence if sizeof(int) > sizeof(char), a promotion 
  23. of char to int may or may not extend the most significant bit.
  24.  
  25.     On the other hand, a conversion of int to char, (if sizeof(int) > 
  26. sizeof(char) ) results in the more significant bits being truncated. In 
  27. line 1 above, the int 'a' is truncated and converted to a char foo1. 
  28. Subsequently, the char foo1 is promoted to an int in the comparison with 
  29. foo2.
  30.  
  31.     Since we cant tell whether the sign bit is extended or not, is it 
  32. wise to use such a comparison if we want to be portable ?
  33.  
  34.     Thank you.
  35.  
  36. --
  37.  
  38. Tey Chee Meng   
  39.  
  40. " Not to take extremes, the middle way is the best "
  41.  
  42.